#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
推荐系统实例演示 (Recommendation System Demo)
展示推荐系统的实际使用效果 (Showcase practical usage of the recommendation system)
"""

import json
import random
from datetime import datetime, timedelta
from recommendation_system import recommendation_system
from integrated_system import Product, Customer, user_manager


def create_demo_customer():
    """创建一个演示用户 (Create a demo user)"""
    print("👤 创建演示用户... (Create demo user...)")
    
    # 创建用户
    customer = Customer(
        user_id="demo_user_001",
        username="演示用户",
        password="123456",
        email="demo@example.com",
        phone="13800138000"
    )
    
    print(f"✅ 用户创建成功 (User created successfully): {customer.username} (ID: {customer.user_id})")
    return customer


def simulate_user_behavior(customer):
    """模拟用户行为数据 (Simulate user behavior data)"""
    print("\n📊 模拟用户行为数据... (Simulating user behavior data...)")
    
    # 获取所有商品
    all_products = Product._load_all_products()
    if not all_products:
        print("❌ 无法加载商品数据 (Failed to load product data)")
        return False
    
    # 模拟用户偏好（喜欢食品和服装）
    preferred_categories = ["Food", "Clothing"]
    preferred_products = [p for p in all_products if p.kind in preferred_categories]
    other_products = [p for p in all_products if p.kind not in preferred_categories]
    
    print(f"📦 总商品数 (Total products): {len(all_products)}")
    print(f"🏷️ 偏好类别 (Preferred categories): {preferred_categories}")
    
    # 模拟浏览行为（偏好商品更多）
    print("\n👀 模拟浏览行为... (Simulating browsing behavior...)")
    for _ in range(15):
        if random.random() < 0.7 and preferred_products:  # 70%概率浏览偏好商品
            product = random.choice(preferred_products)
        elif other_products:
            product = random.choice(other_products)
        else:
            continue
        
        customer.add_viewed_product(product.id)
        print(f"  👁️ 浏览了 (Viewed): {product.name} ({product.kind})")
    
    # 模拟购买行为
    print("\n🛒 模拟购买行为... (Simulating purchase behavior...)")
    for _ in range(5):
        if random.random() < 0.8 and preferred_products:  # 80%概率购买偏好商品
            product = random.choice(preferred_products)
        elif other_products:
            product = random.choice(other_products)
        else:
            continue
        
        quantity = random.randint(1, 2)
        customer.add_purchased_product(product.id, quantity)
        print(f"  🛍️ 购买了 (Purchased): {product.name} x{quantity}")
    
    # 模拟搜索行为
    print("\n🔍 模拟搜索行为... (Simulating search behavior...)")
    search_keywords = ["大米", "衣服", "手机", "书籍", "食品"]
    for keyword in search_keywords[:3]:
        results_count = random.randint(5, 15)
        customer.add_search_history(keyword, results_count)
        print(f"  🔎 搜索了 (Searched): {keyword} (找到 {results_count} 个结果 / found {results_count} results)")
    
    print("✅ 用户行为数据模拟完成！(User behavior data simulation completed)")
    return True


def test_personalized_recommendations(customer):
    """测试个性化推荐 (Test personalized recommendations)"""
    print("\n🧠 个性化推荐测试 (Personalized recommendation test)")
    print("=" * 50)
    
    try:
        recommendations = customer.get_personalized_recommendations(8)
        
        if recommendations:
            print(f"🎯 为您推荐 {len(recommendations)} 个商品 (Recommended {len(recommendations)} products for you):")
            print("-" * 60)
            
            for i, product in enumerate(recommendations, 1):
                print(f"{i:2d}. 📦 {product.name}")
                print(f"     💰 价格 (Price): {product.prize} 元")
                print(f"     🏷️  类别 (Category): {product.kind}")
                print(f"     📍 产地 (Origin): {product.province}")
                print(f"     🆔 ID：{product.id}")
                print("-" * 40)
        else:
            print("📝 暂无个性化推荐结果 (No personalized recommendations yet)")
    
    except Exception as e:
        print(f"❌ 个性化推荐测试失败 (Personalized recommendation test failed): {str(e)}")


def test_algorithm_comparison(customer):
    """测试不同推荐算法对比 (Compare different recommendation algorithms)"""
    print("\n🔬 推荐算法对比测试 (Algorithm comparison test)")
    print("=" * 50)
    
    algorithms = {
        "collaborative": "协同过滤",
        "content": "内容推荐",
        "popularity": "流行度推荐",
        "hybrid": "混合推荐"
    }
    
    for algo_key, algo_name in algorithms.items():
        try:
            recommendations = customer.get_recommendations(5, algo_key)
            print(f"\n🔬 {algo_name} (Algorithm):")
            
            if recommendations:
                for i, product in enumerate(recommendations, 1):
                    print(f"  {i}. {product.name} ({product.kind}) - {product.prize} 元")
            else:
                print("  暂无推荐结果 (No recommendations)")
        
        except Exception as e:
            print(f"  ❌ {algo_name} 算法出错 (Algorithm error): {str(e)}")


def test_category_recommendations(customer):
    """测试分类推荐 (Test category-based recommendations)"""
    print("\n🏷️ 分类推荐测试 (Category recommendation test)")
    print("=" * 50)
    
    categories = ["Food", "Clothing", "Book", "Electronic Products", "Daily product"]
    category_names = {
        "Food": "食品",
        "Clothing": "服装",
        "Book": "图书",
        "Electronic Products": "电子产品",
        "Daily product": "日用品"
    }
    
    for category in categories[:3]:  # 测试前3个类别
        try:
            recommendations = customer.get_category_recommendations(category, 4)
            print(f"\n🏷️ {category_names[category]} 类推荐 (Category recommendations):")
            
            if recommendations:
                for i, product in enumerate(recommendations, 1):
                    print(f"  {i}. {product.name} - {product.prize} 元")
            else:
                print("  暂无推荐结果 (No recommendations)")
        
        except Exception as e:
            print(f"  ❌ {category_names[category]} 类推荐出错 (Category recommendation error): {str(e)}")


def test_trending_products():
    """测试热门商品 (Test trending products)"""
    print("\n🔥 热门商品测试 (Trending products test)")
    print("=" * 50)
    
    try:
        trending = recommendation_system.get_trending_products(days=7, num_recommendations=6)
        
        if trending:
            print("🔥 最近7天热门商品 (Trending products in last 7 days):")
            print("-" * 60)
            
            for i, product in enumerate(trending, 1):
                print(f"{i:2d}. 📦 {product.name}")
                print(f"     💰 价格 (Price): {product.prize} 元")
                print(f"     🏷️  类别 (Category): {product.kind}")
                print(f"     📍 产地 (Origin): {product.province}")
                print("-" * 40)
        else:
            print("📝 暂无热门商品数据 (No trending product data)")
    
    except Exception as e:
        print(f"❌ 热门商品测试失败 (Trending products test failed): {str(e)}")


def test_user_preferences(customer):
    """测试用户偏好分析 (Test user preference analysis)"""
    print("\n📊 用户偏好分析测试 (User preference analysis test)")
    print("=" * 50)
    
    try:
        preferences = recommendation_system.behavior_tracker.get_user_preferences(customer.user_id)
        
        print("📈 您的购物偏好分析 (Your shopping preference analysis):")
        print("-" * 50)
        
        # 类别偏好
        if preferences["categories"]:
            print("🏷️ 最感兴趣的类别 (Most interested categories):")
            for category, count in preferences["categories"].most_common(5):
                print(f"   {category}: {count} 次浏览 / views")
        else:
            print("🏷️ 暂无类别偏好数据 (No category preference data)")
        
        # 价格偏好
        if preferences["price_range"]["min"] != float('inf'):
            print(f"\n💰 价格偏好范围 (Preferred price range): {preferences['price_range']['min']:.1f} - {preferences['price_range']['max']:.1f} 元")
        else:
            print("\n💰 暂无价格偏好数据 (No price preference data)")
        
        # 产地偏好
        if preferences["provinces"]:
            print("\n📍 最感兴趣的产地 (Most interested origins):")
            for province, count in preferences["provinces"].most_common(5):
                print(f"   {province}: {count} 次浏览 / views")
        else:
            print("\n📍 暂无产地偏好数据 (No origin preference data)")
        
        # 行为统计
        print(f"\n📊 行为统计 (Behavior statistics):")
        print(f"   浏览商品 (Viewed products): {len(preferences['viewed_products'])} 个")
        print(f"   购买商品 (Purchased products): {len(preferences['purchased_products'])} 个")
        print(f"   评分商品 (Rated products): {len(preferences['rated_products'])} 个")
        
        # 评分统计
        if preferences["rated_products"]:
            ratings = [data["rating"] for data in preferences["rated_products"].values()]
            avg_rating = sum(ratings) / len(ratings)
            print(f"   平均评分 (Average rating): {avg_rating:.1f} 分")
    
    except Exception as e:
        print(f"❌ 用户偏好分析测试失败 (User preference analysis test failed): {str(e)}")


def test_recommendation_accuracy():
    """测试推荐准确性 (Test recommendation accuracy)"""
    print("\n🎯 推荐准确性测试 (Recommendation accuracy test)")
    print("=" * 50)
    
    # 获取用户偏好
    customer = Customer("test_accuracy", "测试用户 (Test User)", "123456", "test@example.com", "13800138000")
    
    # 模拟用户明确偏好食品
    food_products = [p for p in Product._load_all_products() if p.kind == "Food"]
    
    if food_products:
        # 让用户浏览和购买食品
        for product in food_products[:5]:
            customer.add_viewed_product(product.id)
        
        for product in food_products[:3]:
            customer.add_purchased_product(product.id, 1)
        
        # 获取推荐
        recommendations = customer.get_personalized_recommendations(10)
        
        if recommendations:
            food_recommendations = [p for p in recommendations if p.kind == "Food"]
            accuracy = len(food_recommendations) / len(recommendations) * 100
            
            print(f"📊 推荐准确性分析 (Recommendation accuracy analysis):")
            print(f"   总推荐数 (Total recommendations): {len(recommendations)}")
            print(f"   食品推荐数 (Food recommendations): {len(food_recommendations)}")
            print(f"   准确性 (Accuracy): {accuracy:.1f}%")
            
            if accuracy >= 50:
                print("✅ 推荐系统准确性良好 (Good recommendation accuracy)")
            else:
                print("⚠️ 推荐系统准确性有待提升 (Accuracy needs improvement)")
        else:
            print("📝 暂无推荐结果 (No recommendations)")
    else:
        print("❌ 无法找到食品类商品 (No food products found)")


def run_performance_test():
    """运行性能测试 (Run performance test)"""
    print("\n⚡ 性能测试 (Performance test)")
    print("=" * 50)
    
    import time
    
    customer = Customer("perf_test", "性能测试 (Performance Test)", "123456", "perf@test.com", "13800138000")
    
    # 模拟一些行为数据
    products = Product._load_all_products()[:10]
    for product in products:
        customer.add_viewed_product(product.id)
    
    algorithms = ["collaborative", "content", "popularity", "hybrid"]
    num_tests = 10
    
    for algorithm in algorithms:
        times = []
        for _ in range(num_tests):
            start_time = time.time()
            recommendations = customer.get_recommendations(10, algorithm)
            end_time = time.time()
            times.append(end_time - start_time)
        
        avg_time = sum(times) / len(times)
        min_time = min(times)
        max_time = max(times)
        
        print(f"🔬 {algorithm} 算法 (Algorithm):")
        print(f"   平均响应时间 (Avg response time): {avg_time:.4f} 秒")
        print(f"   最快响应时间 (Fastest): {min_time:.4f} 秒")
        print(f"   最慢响应时间 (Slowest): {max_time:.4f} 秒")


def main():
    """主演示函数 (Main demo function)"""
    print("🎯 推荐系统实例演示 (Recommendation system demo)")
    print("=" * 60)
    
    # 创建演示用户
    customer = create_demo_customer()
    
    # 模拟用户行为
    if not simulate_user_behavior(customer):
        return
    
    # 运行各种测试
    test_personalized_recommendations(customer)
    test_algorithm_comparison(customer)
    test_category_recommendations(customer)
    test_trending_products()
    test_user_preferences(customer)
    test_recommendation_accuracy()
    run_performance_test()
    
    print("\n✅ 推荐系统实例演示完成！(Demo completed)")
    print("\n📝 演示总结 (Demo summary):")
    print("1. ✅ 用户行为数据收集和存储 (Behavior data collection and storage)")
    print("2. ✅ 个性化推荐算法 (Personalized recommendation algorithms)")
    print("3. ✅ 多种推荐算法对比 (Algorithm comparison)")
    print("4. ✅ 分类推荐功能 (Category recommendations)")
    print("5. ✅ 热门商品推荐 (Trending products)")
    print("6. ✅ 用户偏好分析 (User preference analysis)")
    print("7. ✅ 推荐准确性测试 (Recommendation accuracy test)")
    print("8. ✅ 系统性能测试 (Performance test)")
    
    print("\n🎉 推荐系统已成功集成到 Ali Bao Bao 电商平台！(Successfully integrated into Ali Bao Bao platform)")


if __name__ == "__main__":
    main()
